import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import rand_score, adjusted_rand_score


def plot_clu_data(x_pca, y_p, model):  # 聚类可视化
    centers = model.cluster_centers_
    plt.figure(figsize=(10, 8))
    class1 = np.where(y_p == 0)  # 找到y=0的位置
    p1, = plt.plot(np.ravel(x_pca[class1, 0]), np.ravel(x_pca[class1, 1]), 'ro', markersize=8)

    class2 = np.where(y_p == 1)  # 找到y=1的位置
    class3 = np.where(y_p == 2)  # 找到y=2的位置
    p1, = plt.plot(np.ravel(x_pca[class1, 0]), np.ravel(x_pca[class1, 1]), 'ro', markersize=8)
    p2, = plt.plot(np.ravel(x_pca[class2, 0]), np.ravel(x_pca[class2, 1]), 'g^', markersize=8)
    p3, = plt.plot(np.ravel(x_pca[class3, 0]), np.ravel(x_pca[class3, 1]), 'bs', markersize=8)
    p4, = plt.plot(centers[:, 0], centers[:, 1], 'kx', markersize=8)
    plt.xlabel("X1")
    plt.ylabel("X2")
    plt.legend([p1, p2, p3, p4], ["y=0", "y=1", "y=2", "Centers"])
    plt.show()


# 降维可视化
def plot_dr_data(x):
    plt.figure(figsize=(10, 8))
    p, = plt.plot(x[:, 0], x[:, 1], 'mp', markersize=8)
    plt.xlabel("x1")
    plt.ylabel("x2")
    plt.legend([p], ["X_dr"])
    plt.show()


if __name__ == '__main__':
    X, y = make_blobs(n_samples=300,
                      centers=3,
                      n_features=8,
                      cluster_std=5.0,
                      random_state=3)  # 生成数据

    pca = PCA(n_components=2)
    x_dr = pca.fit_transform(X)  # 降维
    # x_dr=X
    plot_dr_data(x_dr)
    for i in range(20):
        # init_centers = np.array([[1.0, -1.0], [-1.0, 1.0], [-12.0, -10.0]])   手动选取初始向量的选取
        model = KMeans(n_clusters=3,
                       init='random',  # 随机选取初始向量
                       n_init=1).fit(x_dr)
        y_predict = model.labels_  # 输出预测标签
        clu_centers = model.cluster_centers_  # 输出聚类中心
        plot_clu_data(x_dr, y_predict, model)
        if i == 19:
            print(y)
            print(y_predict)
            print('RI‘s value :', rand_score(y, y_predict))
            print('ARI‘s value :', adjusted_rand_score(y, y_predict))  #

# print('NMI‘s value :', metrics.normalized_mutual_info_score(y, y_predict))  # NMI值
